package cn.kailangtu.commontools;

import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class AdbUtil {
    private static final String TAG = "Cmd";
    private static final StringBuilder result = new StringBuilder();

    public static boolean run(String cmd) {
        Log.d("SU COMMAND","CMD:"+cmd);
        BufferedReader bufferedReader = null;
        DataOutputStream dos = null;
        String receive = "";

        try {
            Process process = Runtime.getRuntime().exec("su");
            if (process != null) {
                // 经过Root处理的android系统即有su命令
                System.out.println("Cmd run: " + cmd);
                bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                dos = new DataOutputStream(process.getOutputStream());
                dos.writeBytes(cmd + "\n");
                dos.flush();
                dos.writeBytes("exit\n");
                dos.flush();

                String readLine;
                while ((readLine = bufferedReader.readLine()) != null) {
                    receive = readLine;
                    result.append("\n").append(receive);
                }
                Log.d("SU COMMAND","cmd result:" + result);

                process.waitFor();
            }
        } catch (Exception e) {
            Log.d("SU COMMAND","ERR:"+e.getMessage());
            return false;
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public static String getTaskResult() {
        return result.toString();
    }
}
